<!--房源概况-->
<template>
  <a-card
    style="height: 100%; display: flex; flex-direction: column"
    :bodyStyle="{flex: 1, height: 0, padding: '0 24px 24px 24px'}"
  >
    <template #title>
      <a-tabs v-model:activeKey="activeKey" size="small" @change="getData">
        <a-tab-pane
          v-for="item of tabList"
          :key="item.key"
          :tab="item.tab"></a-tab-pane>
      </a-tabs>
    </template>
    <template #extra>
      <a-button
        type="link"
        size="small"
        @click="editClick">更多&nbsp;&gt;</a-button>
    </template>
    <a-spin :spinning="spinning">
      <div class="overview-box">
        <div id="monthIncomeEchart" class="chart"></div>
        <!--  antV G2 4.+ useHtml 属性移除， 暂时不支持使用 html 渲染图例，可以在外部自定义图例  -->
        <!--   自定义图例   -->
        <div class="custom-legend">
          <div
            v-for="(item, index) in data" :key="index"
            class="custom-legend-item"
          >
            <div class="item-count">{{item.total}}</div>
            <div class="item-title">
              <div class="circle" :style="{background: color[index]}"></div>
              <div >{{item.name}}</div>
            </div>
          </div>
        </div>
      </div>
    </a-spin>

  </a-card>
</template>
<script>
import {
  defineComponent,
  computed,
  watch,
  onMounted,
  reactive,
  toRefs, onUnmounted,
} from "vue";
import { message } from "ant-design-vue";
import { Chart } from "@antv/g2";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import _ from "lodash";

export default defineComponent({
  name: "monthIncome",
  components: {

  },
  setup(props, context) {

    const state = reactive({
      data: [],
      color:['#addefd',  '#62daab'],
      spinning: false,
      activeKey: '1',
      tabList: [
        {
          key: '1',
          tab: '本月应收',
        },
        {
          key: '2',
          tab: '本月应支',
        },
      ],
      listTimer: null,
      chart: {},
    })


    // 账单详情
    const editClick = () => {
      utils.goMainRoute({
        name: "billList",
        query: {
          receivable_end_date: ShowDate("-30"),
          settle_status: "3,5",
          bill_status: 1,
        },
      });
    };
    // 获取当前日期前后时间
    const ShowDate = (date) => {
      var num = date;
      let n = num;
      let d = new Date();
      let year = d.getFullYear();
      let mon = d.getMonth() + 1;
      let day = d.getDate();
      if (day <= n) {
        if (mon > 1) {
          mon = mon - 1;
        } else {
          year = year - 1;
          mon = 12;
        }
      }
      d.setDate(d.getDate() - n);
      year = d.getFullYear();
      mon = d.getMonth() + 1;
      day = d.getDate();
      let s =
        year +
        "-" +
        (mon < 10 ? "0" + mon : mon) +
        "-" +
        (day < 10 ? "0" + day : day);
      return s;
    };
    const getData = () => {
      clearTimeout(state.listTimer);
      state.listTimer = setTimeout(() => {
        state.spinning = true;
        request
          .get("/org", "/workbench/monthBillSpread", {tab: state.activeKey})
          .then((res) => {
            state.data = res?.list || [];
            state.chart.annotation().clear(true);
            state.chart.annotation().text({
              position: ['50%', '50%'],
              content: state.activeKey === '1' ? '应收' : '应支',
              style: {
                fontSize: 12,
                fill: '#8c8c8c',
                textAlign: 'center',
              },
              offsetY: -20,
            }).text({
              position: ['50%', '50%'],
              content: Number(state.data.reduce((total, currentValue) => {
                  return total + currentValue.total;
                }, 0)).toFixed(2),
              style: {
                fontSize: 30,
                fill: '#6f6f6f',
                textAlign: 'center',
              },
              offsetY: 10,
            })
            state.chart.changeData(res.list);
            state.chart.render();
            state.spinning = false;
          }).catch((err) => {
          state.spinning = false;
        });
      }, 500)
    }

    const renderChart = () => {
      state.spinning = true;
      state.chart = new Chart({
        container: 'monthIncomeEchart',
        autoFit: true,
      });
      state.chart.coordinate('theta', {
        radius: 0.75,
        innerRadius: 0.8,
      });

      state.chart.scale('percent', {
        formatter: val => {
          val == 0 ? val = null :  val = val + '%';
          return val;
        },
      });

      state.chart.legend(false);

      state.chart.tooltip({
        showCrosshairs: false,
        showMarkers: false,
      })

      state.chart
        .interval()
        .adjust('stack')
        .position('percent')
        .label("percent", {
          autoRotate: false,
          type: 'pie',
          offset: "-50%",
          style: {
            textAlign: "center",
            fill: "#fff",
          },
        })
        .color("name", state.color)
        .style({
          fillOpacity: 1,
        })
        .state({
          active: {
            style: element => {
              const shape = element.shape;
              return {
                lineWidth: 10,
                stroke: shape.attr('fill'),
                strokeOpacity: shape.attr('fillOpacity'),
              };
            },
          },
        });

      // 移除图例点击过滤交互
      state.chart.removeInteraction('legend-filter');
      state.chart.interaction('element-active');
      getData();
      state.chart.render();
    }



    onMounted(() => {
      renderChart();
    });

    onUnmounted(() => {
      if (!_.isEmpty(state.chart)) {
        state.chart.destroy();
      }
    })


    return {
      ...toRefs(state),
      getData,
      editClick,
    };
  },
});
</script>

<style lang="less" scoped>
.circle {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 2px;
}
.overview-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .custom-legend {
    height: 50px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    &-item {
      display: flex;
      flex-direction: column;
      flex: 1;
      align-items: center;
      justify-content: space-around;
      .item-count {
        font-size: 18px;
        font-weight:600;
        color: #666666;
      }
      .item-title {
        display: flex;
        font-size: 12px;
        align-items: center;
      }
      &:not(:last-child) {
        border-right: 1px solid #e9e9e9;
      }
    }
  }
  .chart {
    flex: 1;
  }
}
.icon-primary {
  color: @primary-color;
  font-size: 20px;
}
:deep(.ant-spin-nested-loading) {
  height: 100%;
}
:deep(.ant-spin-container) {
  height: 100%;
}
:deep(.ant-tabs-bar) {
  padding: 0!important;
}
:deep(.ant-tabs-bar) {
  border-bottom: none!important;
}

</style>